package framework.netty1;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class NettyClient {
    private final static String HOST = "127.0.0.1";

    public static void main(String[] args) throws Exception {
        NettyClient.run();
    }

    public static void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();// I/O线程池
        try {
            Bootstrap bs = new Bootstrap();// 客户端辅助启动类
            bs.group(group).channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(HOST, NettyServer.PORT))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        // 进行通道初始化配置
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new ClientHandler());// 添加自定义 Handler
                        }
                    });

            // 同步连接到服务端
            ChannelFuture future = bs.connect().sync();

            // 发送消息
            future.channel().writeAndFlush(Unpooled.copiedBuffer("Hello World", StandardCharsets.UTF_8));

            // 阻塞操作，closeFuture() 开启了一个channel的监听器（这期间channel在进行各项工作），直到链路断开
            future.channel().closeFuture().sync();

        } finally {
            group.shutdownGracefully().sync();
        }
    }

}
